﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using ELearning.API.HandleAttribute;
using ELearning.BLL;
using ELearning.Common;
using ELearning.Common.Helpers;
using ELearning.Common.Oprator;
using ELearning.Models;

namespace ELearning.API.Controllers
{
    /// <summary>
    /// API基类
    /// </summary>
    [RequestAuthorize]
    public class BaseApiController : ApiController
    {
        /// <summary>
        /// 登录token记录操作service
        /// </summary>
        private TLoginTokenService tlLoginTokenService => new TLoginTokenService();

        /// <summary>
        /// 用户操作service
        /// </summary>
        private ESysUserService userService = new ESysUserService();

        /// <summary>
        /// 邀请码日志操作service
        /// </summary>
        private TInviteCodeLogService tInviteCodeLogService => new TInviteCodeLogService();

        /// <summary>
        /// 当前用户信息实体
        /// </summary>
        public OperatorModel CurrentUserModel
        {
            get
            {
                var values = HttpContext.Current.Request.Headers.GetValues("Authorization");
                var authorization = Guid.Empty.ToString();
                if (values.IsNotNull() && values.Length > 0)
                {
                    authorization = values[0];
                    if (Guid.TryParse(authorization, out var g))
                    {
                        var currentUserModel = OperatorProvider.Provider.GetCurrent(authorization);
                        if (currentUserModel == null)
                        {
                            currentUserModel = new OperatorModel();
                            //var m = tlLoginTokenService.Find(i => i.Token == authorization && i.PassDateTime > DateTime.Now);
                            //var user = userService.Find(u => !u.IsDelete && u.UserID == m.UserId) ?? new ESysUser();
                            //currentUserModel = new OperatorModel
                            //{
                            //    Email = user.Email,
                            //    HeadPhoto = user.HeadPhoto,
                            //    LoginName = user.LoginName,
                            //    OrgCode = user.OrgCode,
                            //    MobilePhone = user.MobilePhone,
                            //    Position = user.Position,
                            //    Remark = user.Remark,
                            //    UserId = user.UserID,
                            //    UserIp = IpHelp.GetClientIp(),
                            //    UserName = user.UserName,
                            //    UserType = user.UserType,
                            //    CardNo = user.CardNo
                            //};

                            //OperatorProvider.Provider.AddCurrent(authorization, currentUserModel, m.PassDateTime);
                        }
                        return currentUserModel;
                    }
                }
                return new OperatorModel();
            }
        }

        /// <summary>
        /// 生成邀请码并记录到数据库
        /// </summary>
        /// <param name="orgCode">组织编码,如果生成组织的邀请码，传递组织的编码，如果生成用户的邀请码，则传递用户所属的组织编码</param>
        /// <param name="userId">用户id，如果是为组织生成邀请码，userid可传 Guid.Empty</param>
        /// <returns></returns>
        protected string GetInviteCode(string orgCode, Guid userId)
        {
            #region 生成邀请码

            var sort = tInviteCodeLogService.FindList(p => !p.IsDelete).OrderByDescending(p => p.Sort).FirstOrDefault()?.Sort ?? 0;
            var count = 0;
            var inviteCode = $"{CodeHelper.CreateCodePre()}{sort.ToString().PadLeft(8, '0')}";
            var code = inviteCode;
            var log = tInviteCodeLogService.Find(i => i.InviteCode == code);
            while (log.IsNotNull())//查重，是否有重复邀请码
            {
                sort++;
                inviteCode = $"{CodeHelper.CreateCodePre()}{sort.ToString().PadLeft(8, '0')}";
                var code1 = inviteCode;
                log = tInviteCodeLogService.Find(i => i.InviteCode == code1);
                count++;
                if (count > 5)
                {
                    inviteCode = DateTimeHelper.GetNowTimestamp().ToString();
                    break;
                }
            }

            //邀请码生成成功，存入数据库
            tInviteCodeLogService.AddNoSaveChange(new TInviteCodeLog
            {
                Id = Guid.NewGuid(),
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                IsDelete = false,
                CreateUserId = CurrentUserModel.UserId,
                UpdateUserId = CurrentUserModel.UserId,
                InviteCode = inviteCode,
                OrgCode = orgCode,
                UserId = userId,
                Sort = sort
            });

            #endregion

            return inviteCode;
        }

        /// <summary>
        /// 获取保存失败信息文件地址
        /// </summary>
        protected string GetSavePath()
        {
            var virtualPath = "/UploadFile/Files/ImportFail/";
            var path = HttpContext.Current.Server.MapPath(virtualPath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            var fn = $"导入失败信息{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileFullPath = $"{path}{fn}";
            var downUrl = PictureHelper.GetFileFullPath($"{virtualPath}{fn}");
            return $"{fileFullPath},{downUrl}";
        }
    }
}